import socket
import os
import logging
from qcloud_cos import CosConfig, CosS3Client

logger = logging.getLogger(__name__)

class FaceFusionCOSConfig:
    """FaceFusion COS配置（与GFPGAN共享COS桶）"""
    SECRET_ID = 'AKIDAQTJzVotlSwDH8p2MZw9E855uZHo8F9u'
    SECRET_KEY = 'jGav66wa9XkldKp9JI7kEdqulPq45vZ0'
    BUCKET_PREFIX = 'photoenhancei'
    ACCOUNT_ID = '1259206939'
    CDN_DOMAIN = 'cdn.gongjuxiang.work'
    
    REGION_MAPPING = {
        '10.2.': 'ap-beijing',
        '10.3.': 'ap-shanghai',
        '10.1.': 'ap-guangzhou',
        '10.4.': 'ap-chengdu',
    }
    
    REGION_SHORT_NAMES = {
        'ap-beijing': 'bj',
        'ap-shanghai': 'sh',
        'ap-guangzhou': 'gz',
        'ap-chengdu': 'cd',
    }
    
    def __init__(self):
        self.detected_region = self._detect_region()
        self.region = self.detected_region
        self.region_short = self.REGION_SHORT_NAMES.get(self.region, 'bj')
        self.bucket = f"{self.BUCKET_PREFIX}-{self.region_short}-{self.ACCOUNT_ID}"
        self.internal_domain = f"{self.bucket}.cos-internal.{self.region}.myqcloud.com"
        
        logger.info(f"检测到的地域: {self.detected_region}")
        logger.info(f"COS存储桶: {self.bucket}")
        logger.info(f"内网域名: {self.internal_domain}")
    
    def _detect_region(self):
        """自动检测GPU服务器地域"""
        # 优先使用环境变量
        env_region = os.getenv('GPU_REGION')
        if env_region:
            logger.info(f"使用环境变量地域: {env_region}")
            return env_region
        
        # 通过内网IP检测地域
        try:
            hostname = socket.gethostname()
            local_ip = socket.gethostbyname(hostname)
            
            logger.info(f"检测本机IP: {local_ip}")
            
            for ip_prefix, region in self.REGION_MAPPING.items():
                if local_ip.startswith(ip_prefix):
                    logger.info(f"根据IP段 {ip_prefix} 检测到地域: {region}")
                    return region
            
            logger.warning("无法检测地域，使用默认地域: ap-beijing")
            return 'ap-beijing'
            
        except Exception as e:
            logger.warning(f"地域检测失败: {e}，使用默认地域: ap-beijing")
            return 'ap-beijing'
    
    def get_cos_client(self):
        """获取COS客户端（使用内网域名）"""
        config = CosConfig(
            Region=self.region,
            SecretId=self.SECRET_ID,
            SecretKey=self.SECRET_KEY,
            Domain=self.internal_domain  # 内网域名，免流量
        )
        return CosS3Client(config)
    
    def get_config_info(self):
        """获取配置信息"""
        return {
            'bucket': self.bucket,
            'region': self.region,
            'region_short': self.region_short,
            'internal_domain': self.internal_domain,
            'cdn_domain': self.CDN_DOMAIN
        }
